<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of TorrentController
 *
 * @author mz
 */
class TorrentController extends AtomController {
	public $defaultAction = 'list';
	private $_torrent = null;
	private $user = null;

	private function addNeededFields() {
		$dump = $this->_torrent->getDump();
		Benc::dict_replace($dump, 'info_hash', 'string', $this->_torrent->info_hash);

		$fd = fopen($this->_torrent->torrentfile->getTempName(), 'wb');

		if ($fd !== false) {
			fwrite($fd, Benc::encode($dump));
			fclose($fd);
			return true;
		}
		return false;
	}

	public function actionUpload() {
		$this->_torrent = new Torrent();
		$this->_torrent->scenario = 'upload';
		$user = User::model()->findByPk(Yii::app()->user->id);

		if (isset($_POST['Torrent'])) {
			$this->_torrent->attributes = $_POST['Torrent'];
			$this->_torrent->added = Misc::get_datetime();
			$this->_torrent->torrentfile = CUploadedFile::getInstance($this->_torrent, 'torrentfile');
			$this->_torrent->uploader_id = $user->id;
			
			if ($this->_torrent->checkDump() && $this->_torrent->save()) {
				$this->addNeededFields();
				$this->_torrent->torrentfile->saveAs('torrents/'.$this->_torrent->id.'.torrent');
				Yii::app()->user->setFlash('torrentUploaded', 'Torrent Uploaded Successfully!');
				$this->redirect(array('show', 'id' => $this->_torrent->id));
			}
			else {
				Yii::app()->user->setFlash('torrentUploaded', $this->_torrent->getErrMsg());
			}
		}
		$this->render('upload', array('form' => $this->_torrent));

	}

	public function actionList() {
		$criteria=new CDbCriteria;
		$criteria->order='added DESC';
		$torrentCount = Torrent::model()->count($criteria);

		$pages = new CPagination($torrentCount);
		$pages->pageSize = Yii::app()->params['postsPerPage'];
		$pages->applyLimit($criteria);

		$torrents = Torrent::model()->findAll($criteria);

		$this->render('list',array(
			'torrents'=>$torrents,
			'pages'=>$pages,
		));
	}

	public function actionDownload($id = null) {
		$user = User::model()->findByPk(Yii::app()->user->id);
		$torrent = Torrent::model()->findByPk(isset($id) ? $id : $_GET['id']);
		if ($user !== null && $torrent !== null) {
			$filepath = 'torrents/'.$torrent->id.'.torrent';
			$dump = Benc::decode_file($filepath, filesize($filepath));
			Benc::dict_replace($dump, 'announce', 'string', Yii::app()->params['trackerUrl'].'announce?passkey='.$user->passkey);
			$encoded = Benc::encode($dump);
			header('Content-Type: application/x-bittorrent');
			header("Content-Disposition: attachment; filename=\"{$torrent->name}.torrent\"");
			print($encoded);
		}
	}

	public function actionDelete($id=null) {
		$torrent = Torrent::model()->findByPk($id!==null ? $id : $_GET['id']);
		if ($torrent !== null) {
			unlink('torrents/'.$torrent->id.'.torrent');
			$torrent->delete();
		}
		$this->redirect('torrent');
	}


	public function actionShow() {
		if (!isset($id) && !isset($_GET['id']))
			$this->redirect('/torrent/list');

		$torrent = $this->loadTorrent();
		$file = dirname($_SERVER['SCRIPT_FILENAME']).'/torrents/'.$torrent->id.'.torrent';

		$dump = Benc::decode_file($file, filesize($file));
		$this->render('show', array('torrent' => $torrent, 'dump' => $dump));
	}

	public function loadTorrent($id = null) {
		if($this->_torrent===null) {
			if($id!==null || isset($_GET['id']))
				$this->_torrent = Torrent::model()->findbyPk($id!==null ? $id : $_GET['id']);
			if($this->_torrent === null)
				throw new CHttpException(500,'The requested torrent does not exist.');
		}
		return $this->_torrent;
	}

}
?>
